package com.xj.openapi4j.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xj.dao.InventoryDao;
import com.xj.entity.InvUpdateInfo;
import  com.xj.openapi4j.commons.TokenManager;
import  com.xj.openapi4j.exception.OpenAPIException;
import  com.xj.openapi4j.model.Record;
import com.xj.openapi4j.service.token.U8Token;
import com.xj.openapi4j.service.token.YsToken;
import  com.xj.openapi4j.util.HttpUtil;
import com.xj.openapi4j.util.RequestTool;
import com.xj.util.DateUtils;
import com.xj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 存货信息
 */

@Service
@Slf4j
public class InventoryService  {
	public static   java.util.List<String> inventoryClassList=new ArrayList<>();

	 static {
		 inventoryClassList.add("02003001");
		 inventoryClassList.add("02003002");
		 inventoryClassList.add("02003003");
		 inventoryClassList.add("02003004");
		 inventoryClassList.add("02003005");
		 inventoryClassList.add("02003006");
		 inventoryClassList.add("02003007");
	}


	@Value("${u8AppKey}")
	String u8AppKey;
    @Autowired
	InventoryDao inventoryDao;
	@Value("${u8AppSecret}")
	String u8AppSecret;
	@Value("${fromAccount}")
	String from_account;

	@Autowired
	U8Token u8Token;
	@Autowired
	YsToken ysToken;
    @Autowired
	UnitService unitService;
	private JSONObject getU8Inventory(String id) throws OpenAPIException {
		JSONObject record;
		try {
			Map<String, String> paramMap = new HashMap();
			paramMap.put("from_account", from_account);
			paramMap.put("to_account", from_account);
			paramMap.put("id", id);
			paramMap.put("app_key", u8AppKey);
			paramMap.put("app_secret", u8AppSecret);
		//	String url = this.createURL("inventory/get", paramMap);
			String url = "https://api.yonyouup.com/api/inventory/get";
			String str = RequestTool.doGet(url, paramMap);
			log.debug(url);
			record = JSONObject.parseObject(HttpUtil.get(url));
		} catch (Exception e) {
			throw new OpenAPIException(e.getMessage(), e);
		}
		return record;
	}

	//定时任务，自动同步增量
	public  void  transIncrement() throws Exception{
		List<InvUpdateInfo> list= inventoryDao.getInvUpdateInfoByCategory("inventory");
		log.info("----------inventoryDao.getInvUpdateInfoByCategory  inventor {} ",list.size());
		Set<String> set=list.stream().map(obj->obj.getCinvcode()).collect(Collectors.toSet());
		for(String cinvcode:set){
			try {
				transInventory(null, cinvcode);
			}catch (Exception err){
				err.printStackTrace();
				log.error(err.getMessage());
			}
		}
		log.info("begin delete  inventory list");
		inventoryDao.deleteAll(list);
	}


	public  void transInventory(Integer day,String cinvcode) throws Exception{
		JSONArray data=getU8InvenArray(day,cinvcode);
		transInventory(data);
	}

	private JSONArray getU8InvenArray(Integer day,String cinvcode) throws OpenAPIException {
		try {
			String url = "https://api.yonyouup.com/api/inventory/batch_get";
			Map<String, String> paramMap = new HashMap();
			paramMap.put("from_account",from_account);
			paramMap.put("to_account", from_account);
			paramMap.put("app_key", u8AppKey);
			paramMap.put("token", u8Token.getToken());
			if(StringUtils.isNotEmpty(cinvcode)){
				paramMap.put("code_begin",cinvcode);
				paramMap.put("code_end",cinvcode);
			}else {
				if(day==null){
					day=50;
				}
				paramMap.put("modifydate_begin", DateUtils.getAddDate(DateUtils.yyyy_MM_dd,(-1)*day));
				paramMap.put("modifydate_end",DateUtils.getAddDate(DateUtils.yyyy_MM_dd,1));
			}

			String str = RequestTool.doGet(url, paramMap);
			log.debug(url);
			JSONObject	jsonObject = JSONObject.parseObject(str);
			if("0".equals(jsonObject.getString("errcode"))){
				JSONArray jsonArray=jsonObject.getJSONArray("inventory");
				JSONArray result=new JSONArray();
				for(int i=0;i<jsonArray.size();i++){
					JSONObject info=jsonArray.getJSONObject(i);
				    String inventoryClasscode=info.getString("sort_code");
                    if(inventoryClassList.contains(inventoryClasscode)){
						result.add(info);
					}
				}
				return jsonArray;
			}else {
				throw  new  Exception(jsonObject.getString("errmsg"));
			}
		} catch (Exception e) {
			throw new OpenAPIException(e.getMessage(), e);
		}
	}
	

	private   void  transInventory(JSONArray datas) throws  Exception{
         if(datas==null|| datas.size()==0){
			 return;
		 }
		 for(int i=0;i<datas.size();i++){
			 JSONObject data=datas.getJSONObject(i);
			 JSONObject body=new JSONObject();
			 String prodcode=data.getString("code");
			 body.put("code",prodcode);
			 body.put("orgCode","001");
			 JSONObject name=new JSONObject();
			 name.put("simplifiedName",data.getString("name"));
			 body.put("name",name);
			 JSONObject modelDescription=new JSONObject();
			 modelDescription.put("simplifiedName",data.getString("specs"));
			 body.put("modelDescription",modelDescription);
			 body.put("useSku","1");
			 JSONObject detail=new JSONObject();
			 detail.put("inspectionType",0);
			 detail.put("businessAttribute","1,3,7");
			 detail.put("saleChannel","1,2,3,4");
			 String unitcode=data.getString("main_measure");
             String unitname=data.getString("ccomunitname");
			 boolean isnormal= unitService.checkYSUnit(unitcode,unitname);
			 if(!isnormal){
				 log.info("存货{],计量单位编码{]，名称{}，不能导入",prodcode,unitcode,unitname);
				 continue;
			 }
			 detail.put("purchaseUnitCode",unitcode);
			 detail.put("purchasePriceUnitCode",unitcode);
			 detail.put("inspectionUnitCode",unitcode);
			 detail.put("main_measure",unitcode);
			 detail.put("stockUnitCode",unitcode);
			 detail.put("produceUnitCode",unitcode);
			 detail.put("batchUnitCode",unitcode);
			 detail.put("batchPriceUnitCode",unitcode);
			 detail.put("onlineUnitCode",unitcode);
			 detail.put("offlineUnitCode",unitcode);
			 detail.put("requireUnitCode",unitcode);
             detail.put("batchPriceUnitCode",unitcode);
			 JSONObject receiptName=new JSONObject();
			 receiptName.put("simplifiedName",data.getString("name"));
			 //开票名称
		//	 detail.put("receiptName",receiptName);
			 detail.put("incomeTaxRatesCode","VATR1");
             detail.put("outTaxRateCode","VATR1");
			 //排序号 long
			 if(prodcode.matches("\\d+")){
				 detail.put("order",prodcode);
			 }else {
				 detail.put("order",999999);
			 }

			 //启用状态
			 detail.put("stopstatus",false);
			 detail.put("orderLoadAndUnloadStatus",true);
			 detail.put("canSale",true);
			 detail.put("receiptWarehouseCode","bzp");
			 detail.put("deliveryWarehouseCode","bzp");
			 detail.put("returnWarehouseCode","bzp");
			 detail.put("valueManageType",0);
			 body.put("detail",detail);

			 body.put("manageClassCode",data.getString("sort_code"));
			 //物料类型-通用物料
			 body.put("transTypeCode","SYCSR002");
			 body.put("productClassCode",data.getString("sort_code"));
			 body.put("realProductAttribute",1);
			 body.put("realProductAttributeType",1);
			 //2:使用物料自己的计量单位
			 body.put("unitUseType",2);
			 //启用辅计量
			 body.put("enableAssistUnit",false);
			 body.put("unitCode",unitcode);
			 body.put("mainUnitCount",1);
			 String token=ysToken.getToken();
			 String requestUrl="https://c3.yonyoucloud.com/iuap-api-auth/yonbip/digitalModel/product/add?access_token="+token;
			 try {
				 String str = HttpUtil.post(requestUrl, body.toJSONString());
				 log.info(str);
			 }catch (Exception err){
				 err.printStackTrace();
			 }

		 }


	}
	


}
